<?php
/**
 * BFL API 代理脚本 - 免费主机专用
 * 解决前端跨域问题
 */

// 设置 CORS 头部，允许前端访问
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, x-key, Accept');
header('Content-Type: application/json; charset=utf-8');

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// 获取请求参数
$action = $_GET['action'] ?? '';
$endpoint = $_GET['endpoint'] ?? 'global';

// BFL API 配置
$BFL_ENDPOINTS = [
    'global' => 'https://api.bfl.ai',
    'us' => 'https://api.us.bfl.ai',
    'eu' => 'https://api.eu.bfl.ai',
    'us1' => 'https://api.us1.bfl.ai',
    'eu1' => 'https://api.eu1.bfl.ai'
];

// 验证端点
if (!isset($BFL_ENDPOINTS[$endpoint])) {
    http_response_code(400);
    echo json_encode(['error' => '无效的端点']);
    exit();
}

$base_url = $BFL_ENDPOINTS[$endpoint];

try {
    switch ($action) {
        case 'generate':
            handleGenerate($base_url);
            break;
        case 'poll':
            handlePoll();
            break;
        default:
            http_response_code(400);
            echo json_encode(['error' => '无效的操作']);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => '服务器错误: ' . $e->getMessage()]);
}

/**
 * 处理图片生成请求
 */
function handleGenerate($base_url) {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['error' => '只支持 POST 请求']);
        return;
    }

    // 获取请求体
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (!$data || !isset($data['prompt'])) {
        http_response_code(400);
        echo json_encode(['error' => '缺少必要参数']);
        return;
    }

    // 获取 API 密钥
    $api_key = $_SERVER['HTTP_X_KEY'] ?? '';
    if (empty($api_key)) {
        http_response_code(401);
        echo json_encode(['error' => '缺少 API 密钥']);
        return;
    }

    // 准备请求数据
    $request_data = [
        'prompt' => $data['prompt'],
        'width' => $data['width'] ?? 1024,
        'height' => $data['height'] ?? 576,
        'prompt_upsampling' => $data['prompt_upsampling'] ?? true,
        'safety_tolerance' => $data['safety_tolerance'] ?? 2,
        'output_format' => $data['output_format'] ?? 'jpeg'
    ];

    // 发送请求到 BFL API
    $url = $base_url . '/v1/flux-pro-1.1';
    $response = makeRequest($url, 'POST', $request_data, [
        'Content-Type: application/json',
        'x-key: ' . $api_key
    ]);

    echo $response;
}

/**
 * 处理轮询请求
 */
function handlePoll() {
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        http_response_code(405);
        echo json_encode(['error' => '只支持 GET 请求']);
        return;
    }

    $polling_url = $_GET['url'] ?? '';
    if (empty($polling_url)) {
        http_response_code(400);
        echo json_encode(['error' => '缺少轮询 URL']);
        return;
    }

    // 获取 API 密钥
    $api_key = $_SERVER['HTTP_X_KEY'] ?? '';
    if (empty($api_key)) {
        http_response_code(401);
        echo json_encode(['error' => '缺少 API 密钥']);
        return;
    }

    // 发送轮询请求
    $response = makeRequest($polling_url, 'GET', null, [
        'Accept: application/json',
        'x-key: ' . $api_key
    ]);

    echo $response;
}

/**
 * 发送 HTTP 请求
 */
function makeRequest($url, $method = 'GET', $data = null, $headers = []) {
    $ch = curl_init();

    // 基本 cURL 设置
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT => 'XinYu-GuoYun/1.0 PHP-Proxy'
    ]);

    // 设置请求方法
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
    }

    // 设置请求头
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    // 执行请求
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);

    curl_close($ch);

    // 检查 cURL 错误
    if ($error) {
        http_response_code(500);
        return json_encode(['error' => 'cURL 错误: ' . $error]);
    }

    // 设置响应状态码
    http_response_code($http_code);

    return $response;
}

/**
 * 记录日志（可选）
 */
function logRequest($message) {
    $log_file = __DIR__ . '/proxy.log';
    $timestamp = date('Y-m-d H:i:s');
    $log_entry = "[$timestamp] $message" . PHP_EOL;
    file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
}

// 记录请求（可选，用于调试）
if (isset($_GET['debug'])) {
    $request_info = [
        'method' => $_SERVER['REQUEST_METHOD'],
        'action' => $_GET['action'] ?? 'none',
        'endpoint' => $_GET['endpoint'] ?? 'none',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ];
    logRequest('Request: ' . json_encode($request_info));
}
?>
